/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pgpproj.pgpframework.authentication;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.Signature;
import java.security.SignatureException;
import java.security.spec.InvalidKeySpecException;
import java.util.logging.Level;
import java.util.logging.Logger;
import pgpproj.pgpframework.authentication.algorithm.SignatureEnum;
import pgpproj.pgpframework.util.CryptoUtil;

/**
 *
 * @author ufabc
 */
public class VerifySignatureActor {

    Signature signatureEngine;

    public VerifySignatureActor() {
        try {
            this.signatureEngine = Signature.getInstance(SignatureEnum.SHA256withRSA);
            
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(VerifySignatureActor.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    public boolean doVerifySignature(String filename, byte[] assinatura) {

        PublicKey key = readKeyfromFile(filename);

        boolean isVerified = false;
        try {
            signatureEngine.initVerify(key);
            isVerified = signatureEngine.verify(assinatura);
        } catch (SignatureException se) {
            isVerified = false;
        } catch (InvalidKeyException ex) {
            Logger.getLogger(VerifySignatureActor.class.getName()).log(Level.SEVERE, null, ex);
        }

        return isVerified;
    }

    public boolean doVerifySignature(PublicKey key, byte[] assinatura) {

         boolean isVerified = false;
        try {
           
            signatureEngine.initVerify(key);
            isVerified = signatureEngine.verify(assinatura);
        }  catch (SignatureException se) {
            isVerified = false;
        } catch (InvalidKeyException ex) {
            Logger.getLogger(VerifySignatureActor.class.getName()).log(Level.SEVERE, null, ex);
        }

        return isVerified;
    }

    private PublicKey readKeyfromFile(String filename) {
        PublicKey publicKey = null;
        try {
            publicKey = CryptoUtil.loadPublicKey(new File("/" + filename + ".pubkey"), "RSA");
        } catch (IOException ex) {
            Logger.getLogger(VerifySignatureActor.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(VerifySignatureActor.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InvalidKeySpecException ex) {
            Logger.getLogger(VerifySignatureActor.class.getName()).log(Level.SEVERE, null, ex);
        }
        return publicKey;

    }
}
